In computer programming, the proxy pattern is a software design pattern which is a class functioning as an interface to something else. The proxy could interface to anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate. In short, a proxy is a wrapper or agent object that is being called by the client to access the real serving object behind the scenes. Use of the proxy can simply be forwarding to the real object, or can provide additional logic. In the proxy, extra functionality can be provided, for example caching when operations on the real object are resource intensive, or checking preconditions before operations on the real object are invoked. For the client, usage of a proxy object is similar to using the real object, because both implement the same interface.
When accessing sensitive objects, for example, it should be possible to check that clients have the needed access rights.
This makes it possible to work through a Proxy object to perform additional functionality when accessing a subject, like checking the access rights of clients accessing a sensitive object.
To act as a substitute for a subject, a proxy must implement the Subject interface. Clients can't tell whether they work with a subject or its proxy.
See also the UML class and sequence diagram below.
In the above UML class diagram, the Proxy class implements the Subject interface so that it can act as substitute for Subject objects. It maintains a reference (realSubject) to the substituted object (RealSubject) so that it can forward requests to it (realSubject.operation()).
The sequence diagram shows the run-time interactions: The Client object works through a Proxy object that controls the access to a RealSubject object. In this example, the Proxy forwards the request to the RealSubject, which performs the request.
using std::string; using std::unique_ptr;
// Subject Interface class Image { public:
virtual void display() const = 0;
virtual ~Image() = default;
};
// Real Subject (expensive to load) class RealImage : public Image { private:
string filename;
public:
explicit RealImage(const string& file):
filename{file} {
loadFromDisk();
}
void display() const override {
std::println("Displaying image: {}", filename);
}
private:
void loadFromDisk() const {
std::println("Loading image from disk: {}", filename);
}
};
// Proxy (controls access to RealImage) class ProxyImage : public Image { private:
string filename; mutable unique_ptrpublic:realImage; // lazily created
explicit ProxyImage(const string& file):
filename{file} {}
void display() const override {
if (!realImage) {
std::println("(Proxy) Loading image on demand...");
realImage = std::make_unique(filename);
}
realImage->display();
}
};
// Client code int main() {
Image* img = new ProxyImage("photo.png");
// First display (should load)
img->display();
// Second display (should use cached image)
img->display();
delete img;
return 0;
}
|
|